package com.tc.jetbrick;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.layout.font.FontProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 将html字符串保存为pdf文件，工具类
 * @author henry01.he
 */
public class HtmlToPdfUtil {

    private final static Logger logger = LoggerFactory.getLogger(HtmlToPdfUtil.class);
    
    // itext7组件的转换器
    private static ConverterProperties properties = new ConverterProperties();
    // itext7组件的字体
    private static final String[] FONTS = {
            HtmlToPdfUtil.class.getClassLoader().getResource("fonts/simsun.ttf").getPath(),
            HtmlToPdfUtil.class.getClassLoader().getResource("fonts/SourceHanSerifSC-Bold.otf").getPath(),
    };

    static {
        try {
            initFontProvider();
        } catch (Exception e) {
            logger.error("init setFontProvider error:", e);
        }
    }

    /**
     * 初始化itext7组件的字体
     * @throws IOException
     */
    private static void initFontProvider() throws IOException {
        FontProvider fontProvider = new DefaultFontProvider(false, false, false);
        for (String font : FONTS) {
            FontProgram fontProgram = FontProgramFactory.createFont(font);
            fontProvider.addFont(fontProgram);
        }
        properties.setFontProvider(fontProvider);
    }

    /**
     * 将html字符串保存为pdf文件，itext7组件实现
     * @param htmlSource
     * @param pdfDestFileName
     * @throws Exception
     */
    public static void html2PdfByItext7(String htmlSource, String pdfDestFileName) throws Exception {
        if (properties.getFontProvider() == null) {
            initFontProvider();
        }

        FileOutputStream fos = new FileOutputStream(pdfDestFileName);
        HtmlConverter.convertToPdf(htmlSource, fos, properties);
    }
}